2023/12/231806字符

Object

对象内部语法简写

let name = 'bozai';
let age = 18;
let json = {
    name,       //== name : name
    age,        //== age : age
    show () {               // show : function(){
        return this.name;   //     return this.name;
    }                       // }
};
console.log(json);  //--> {name: "bozai", age: 18, show: ƒ}
console.log(json.show());  //--> bozai

Object.is()

Object.is(NaN, NaN);  //--> true  视觉上相等

Object.assign() 合并对象

let obj1 = {a : 1},
    obj2 = {a : 2, b : 2},
    obj3 = {c : 3};
let obj4 = Object.assign({}, obj1, obj2, obj3);  // 合并对象
console.log(obj4);  //--> {a: 2, b: 2, c: 3} 

Object.setPrototypeOf() 指定原型对象

Object.setPrototypeOf(obj1, obj2); // == obj1._proto_ = obj2  规定原型对象为 obj2

Object.keys() Object.values() Object.entries()

let {keys, values, entries} = Object;
let obj = {
    a : 1,
    b : 2,
    c : 3
};

for(let key of keys(obj)){
    console.log(key);  //--> a b c  拿到对象的 key 值
}
for(let value of values(obj)){
    console.log(value);  //--> 1 2 3  拿到对象的 value 值
}
for(let item of entries(obj)){
    console.log(item);  //--> ["a", 1] ["b", 2] ["c", 3]
}

Object.fromEntries() 对象转数组

const newObj = Object.entries(obj);  //--> [['a', 1], ['b', 2], ['c', 3]]  对象转数组
Object.fromEntries(newObj);  //--> {a: 1, b: 2, c: 3}  数组转对象

Object.getOwnPropertyNames()

const obj = {
    a: 1, b: 2, c: 3, 4: 1, 5: 3, 0: 2
}
// 数字优先排列,会打乱对象
const prop = Object.getOwnPropertyNames(obj);  //--> 0: "0", 1: "4", 2: "5", 3: "a", 4: "b", 5: "c"